package com.pi.pro.xcmg.am.was.web.cust.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.pi.common.CodesConstants;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.model.AbstractEntity;
import com.pi.framework.core.model.IEditable;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.core.validator.DataValidator;
import com.pi.framework.util.JxlsReader;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.inventory.InventoryChangeActionDto;
import com.pi.wms.entity.TwaInventoryDetails;
import com.pi.wms.entity.TwmBasMaterial;
import com.pi.wms.entity.TwtActTaskList;
import com.pi.wms.service.*;
import com.pi.wms.vo.inventory.InventoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Controller
@RequestMapping("/inventory/kitinv")
public class KitInventoryController extends BaseInventoryController<TwaInventoryDetails, Long> {

	@Autowired
	private InventoryDetailsService service;

    @Autowired
    private DataValidator validator;

	@Override
	protected ICrudService<TwaInventoryDetails, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "kitinv";
	}

	@Override
	protected TwaInventoryDetails newModel(HttpServletRequest request) {
		return new TwaInventoryDetails();
	}

	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		Long userId = SecurityUtils.getLoginUserId();
		query.put("userId", userId.toString());
		query.put("reservecode", XcmgAmConstants.WORK_SOURCE_KIT);
		super.prepareDatatableConditions(query, input);
	}

	@PostMapping("addtoso")
	public String addtoSoDocument(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		String batchnum=TextUtils.genBatchNumber();
		if  ((ids != null) && (ids.length >0)) {
			for (Long id:ids){
				m=this.wasCustomWorkService.addtoKitSoByInventory(batchnum, id, SecurityUtils.getLoginUsername());
				if (m==null){
					m="发生异常,请联系系统管理员";
				}
				if(!StringUtils.isNullOrBlank(m)){
					addErrorMessage(redirectAttributes, "追加出库失败:"+m);
					return this.redirect("");
				}
				//addSuccessMessage(redirectAttributes, "删除成功");
			}
			addSuccessMessage(redirectAttributes, "追加出库成功");
		}
		return this.redirect("");
	}

    @PostMapping("createso")
    public String createSoDocument(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));
        String m="";
        String batchnum=TextUtils.genBatchNumber();
        if  ((ids != null) && (ids.length >0)) {
            for (Long id:ids){
                m=this.wasCustomWorkService.createKitSoByInventory(batchnum, id, SecurityUtils.getLoginUsername());
                if (m==null){
                    m="发生异常,请联系系统管理员";
                }
                if(!StringUtils.isNullOrBlank(m)){
                    addErrorMessage(redirectAttributes, "追加出库失败:"+m);
                    return this.redirect("");
                }
                //addSuccessMessage(redirectAttributes, "删除成功");
            }
            addSuccessMessage(redirectAttributes, "追加出库成功");
        }
        return this.redirect("");
    }

	@GetMapping("del/{id}")
	public String del(@PathVariable("id") Long id, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		if (id != null) {
			m=this.delete(id);
			if (m==null){
				m="发生异常,请联系系统管理员";
			}
			if (CodesConstants.COMMON_STATUS_SUCCESS.equalsIgnoreCase(m)){
				m="";
			}
			if(!com.pi.common.utils.StringUtils.isNullOrBlank(m)){
				addErrorMessage(redirectAttributes, "删除失败:"+m);
				return this.redirect("");
			}
			addSuccessMessage(redirectAttributes, "删除数据成功");
		}
		return this.redirect("");
	}

	@PostMapping("del")
	public String del(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		if (ids != null && ids.length > 0) {
			for (Long id:ids){
				m=this.deleteline(id);
				if (m==null){
					m="发生异常,请联系系统管理员";
				}
				if (CodesConstants.COMMON_STATUS_SUCCESS.equalsIgnoreCase(m)){
					m="";
				}
				if(!StringUtils.isNullOrBlank(m)){
					addErrorMessage(redirectAttributes, "删除失败:"+m);
					return this.redirect("");
				}
				//addSuccessMessage(redirectAttributes, "删除成功");
			}
			addSuccessMessage(redirectAttributes, "删除数据成功");
		}
		return this.redirect("");
	}

	private String deleteline(Long id){
		String m="";
		if (id==null){
			m="无效的库存ID";
			return m;
		}
		TwaInventoryDetails storage=getCrudService().findById(id);
		if (storage==null){
			m="找不到库存,请确认是否已被其他用户删除.库存明细ID="+String.valueOf(id);
			return m;
		}
		if (storage != null && storage instanceof IEditable && !((IEditable) storage).isEditable()) {
			m="该数据为系统固定不可编辑，请选择其他操作!";
			return m;
		}
		BigDecimal qty=storage.getQtyAllocated();
		if ((qty!=null) && (qty.compareTo(BigDecimal.ZERO)>0)){
			m="库存已经分配出库,不能直接删除.托盘码="+storage.getContainNumber()+",箱码="+storage.getTraceNumber();
			return m;
		}
		String contNumber=storage.getContainNumber();
		List<TwtActTaskList> tasks=null;
		try{
			tasks=taskService.queryWorkingTasks("", contNumber);
			if ((tasks!=null) && (tasks.size()>0)){
				m="尚有任务执行,不能删除.托盘码="+contNumber;
				return m;
			}
		}catch(Exception e){
			m=e.getMessage();
			return m;
		}
		try{
			//
			Long stockid=storage.getId();
			this.service.trace("delete",stockid,contNumber,"",storage);
			//TODO:HU/20201103
			String batchNum= TextUtils.genBatchNumber();
			log.info("Controller InventoryController del//{batchnum:{}, storageid:{}, mat:{}, lotnoid:{}, qty:{}, allocateqty:{}, containnum:{}, tracenum:{}, loc:{}, worker:{}}",
					batchNum, storage.getId(), storage.getMaterialId(), storage.getLotnoId(), storage.getQty(), storage.getQtyAllocated(), storage.getContainNumber(), storage.getTraceNumber(), storage.getLocCode(), SecurityUtils.getLoginUsername());

			m=this.service.delete(storage.getId(),
					storage.getContainNumber(), storage.getTraceNumber(),
					"", "", "",
					"", "",
					"","","","","","","","","",  "",
					SecurityUtils.getLoginUsername());
			//service.delete(stock);
			this.service.traceDone("delete", stockid, contNumber, m);
			if (!com.pi.common.utils.StringUtils.isNullOrBlank(m)){
				return m;
			}
			//
			InventoryChangeActionDto changeAction=new InventoryChangeActionDto();
			changeAction.setOperationType(WmsConstants.TRANS_TYPE_REMOVE);
			changeAction.setWorker(SecurityUtils.getLoginUsername());
			this.transService.delete(batchNum,storage,changeAction);
		}catch(Exception e){
			m=e.getMessage();
		}
		return m;
	}

	@Override
    @PostMapping({"/export"})
    public ModelAndView export(@RequestParam final Map<String, Object> query, DataTablesInput input) {
        query.put("reservecode", XcmgAmConstants.WORK_SOURCE_OTHER);
        String inputParams = "";
        if(query.get("input") != null) {
            inputParams = query.get("input").toString();
        }
        if(com.pi.common.utils.StringUtils.isNotEmpty(inputParams)) {
            input = (DataTablesInput) JSONArray.parseObject(inputParams, DataTablesInput.class);
        }
        input.setLength(Integer.valueOf(-1));
        String ymd = DateUtils.format(new Date(), "yyyyMMddHHmmss");
        final DataTablesInput ins = input;
        CsvExporter<TwaInventoryDetails> exporter =  this.createExporter(query, ins, this.getMaterials(), this.getLotattrs());
        return new ModelAndView(new CsvView(exporter, "inventory_list_" + ymd));
    }

    @GetMapping(value = { "/import" })
	public String importIndex(Model model,  HttpServletRequest request, RedirectAttributes redirectAttributes) {
		return super.view(getPrefix() + "_import");
	}

	@PostMapping(value = { "/upload" })
	public String upload(@RequestParam MultipartFile file, Model model, String chkUpdate, HttpServletRequest request,
                         RedirectAttributes redirectAttributes) {
		if (file != null) {
			List<InventoryVo> inventoryList = new ArrayList<InventoryVo>();
			Map<String, Object> beans = new HashMap<String, Object>();
			beans.put("inventoryList", inventoryList);
			try {
				List<String> errors = JxlsReader.readXls(
						new ClassPathResource("/templates/inventory/inventory.xml").getInputStream(), file.getInputStream(),
						beans);
				if (errors != null && !errors.isEmpty()) {
					addErrorMessage(redirectAttributes, (String[]) errors.toArray(new String[0]));
					return "redirect:" + getRequestMapping() + "/import";
				}

				String message = validator.validateMessage(inventoryList);
				if (message != null) {
					addErrorMessage(redirectAttributes, "导入文件验证有错误! " + message);
					redirectAttributes.addFlashAttribute("hasError", true);
				}else {
					try {
						boolean isUpdate = "1".equals(chkUpdate);
						service.importFrom(inventoryList, isUpdate);
						redirectAttributes.addFlashAttribute("hasError", false);
						addSuccessMessage(redirectAttributes, "数据导入成功!");
					} catch (Exception e) {
						addErrorMessage(redirectAttributes, e.getMessage());
						redirectAttributes.addFlashAttribute("hasError", true);
					}
				}
				redirectAttributes.addFlashAttribute("inventoryList", inventoryList);
			} catch (IOException e) {
				e.printStackTrace();
				addErrorMessage(redirectAttributes, "读取文件异常:" + e.getLocalizedMessage());
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage(redirectAttributes, "数据导入异常:" + e.getLocalizedMessage());
			}
		} else {
			addErrorMessage(redirectAttributes, "上传文件为空!");
		}
		return "redirect:" + getRequestMapping() + "/import";
	}

	
}
